package com.hmkj.admin.controller.seller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.admin.utils.AdminSessionHelper;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.seller.SellerModel;
import com.hmkj.core.po.seller.Seller;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.seller.SellerService;
import com.hmkj.core.service.user.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class SellerJsonController extends GenericController<Integer, Seller> {

    @Autowired
    private SellerService sellerService;
    @Autowired
    private UserService userService;

    /**
     * 销售列表
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping("/seller/list.json")
    @RequiresPermissions("sys:seller:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (admin.getRoleId() == Enum.ONE_ROLE_ID || admin.getRoleId() == Enum.TWO_ROLE_ID || admin.getRoleId() == Enum.THREE_ROLE_ID) {
            User user = userService.selectByPrimaryKey(admin.getUserId());
            List<User> userList = userService.listPartnerByLevel(user.getCode(), 0);
            String userIds = "0";
            if (CollectionUtils.isNotEmpty(userList)) {
                userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
            }
            ObjectMapper mapper = new ObjectMapper();
            DtGrid dtGrid1 = mapper.readValue(dtGridPager, DtGrid.class);
            Map<String, Object> dtGridFastQueryParameters = dtGrid1.getFastQueryParameters();
            dtGridFastQueryParameters.put("in_userId", userIds);
            dtGrid1.setFastQueryParameters(dtGridFastQueryParameters);
            dtGridPager = dtGrid1.toJsonString();
        }
        dtGrid = sellerService.getDtGridList(dtGridPager, SellerModel.class);
        //查找代理商类型和代理商销售上级代理商
        for (Object obj : dtGrid.getExhibitDatas()) {
            LinkedHashMap seller = (LinkedHashMap) obj;
            Integer userId = (int) seller.get("userId");
            if (userId != null) {
                User user = userService.selectByPrimaryKey(userId);
                if (user.getUserType() == Enum.UserType.NEXTSELLER.getValue()) {
                    seller.put("sellerType", Enum.UserType.NEXTSELLER.getName());
                } else if (user.getUserType() == Enum.UserType.AGENTSELLER.getValue()) {
                    seller.put("sellerType", Enum.UserType.AGENTSELLER.getName());
                    //查询上级代理商类型，用户名

                    //上级代理商
                    Integer level = user.getLevel();
                    Integer parentId = user.getInviteId();
                    User parentUser = null;

                    if (null != parentId) {
                        if (level > 1) {
                            //上级代理商
                            for (int i = level - 1; i > 0; i--) {
                                parentUser = userService.selectByPrimaryKey(parentId);
                                Integer p = parentUser.getUserType();
                                if (parentUser != null && (p == Enum.UserType.ONELEVEL.getValue() || p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue())) {
                                    seller.put("parentName", parentUser.getUserName());
                                    break;
                                }
                                parentId = parentUser.getInviteId();
                            }
                        }

                    }
                }
            }
        }
        return dtGrid;
    }

    @ResponseBody
    @RequiresPermissions("sys:seller:edit")
    @RequestMapping(value = "seller/edit.json", method = RequestMethod.POST)
    public ResultEntity editSeller(Seller seller) throws Exception {
        if(null == seller.getId()){
            throw new BussinessException("参数错误");
        }
        if(StringUtils.isBlank(seller.getFeeScale())){
            throw new BussinessException("请输入佣金比例");
        }
        if(seller.getFeeScale().toString().length()>3){
            throw new BussinessException("佣金长度不能超过3位");
        }
        if (seller.getFeeScale().compareTo(BigDecimal.ZERO) == -1 || seller.getFeeScale().compareTo(new BigDecimal(100)) == 1) {
            throw new BussinessException("佣金比例应在0~100之间");
        }
        if (seller.getAllCustomer() != Seller.ALLCUSTOMER.T1.code && seller.getAllCustomer() != Seller.ALLCUSTOMER.T2.code) {
            throw new BussinessException("是否可以查看所有用户状态有误");
        }
        if (seller.getCustomerPhone() != Seller.CUSTOMERPHONE.T1.code && seller.getCustomerPhone() != Seller.CUSTOMERPHONE.T2.code) {
            throw new BussinessException("是否可以查看客户电话状态有误");
        }
        Seller sell = sellerService.selectByPrimaryKey(seller.getId());
        if(sell == null){
            throw new BussinessException("销售不存在");
        }else{
            sell.setAllCustomer(seller.getAllCustomer());
            sell.setCustomerPhone(seller.getCustomerPhone());
            sell.setFeeScale(seller.getFeeScale().divide(BigDecimal.valueOf(10000)));
            sellerService.updateByPrimaryKeySelective(sell);
        }
        return ok();
    }
}
